package com.polaris.live.widget.avatar

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.annotation.DrawableRes
import androidx.constraintlayout.widget.ConstraintLayout
import com.bumptech.glide.Glide
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.databinding.WidgetAvatarBinding
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.avatar

/**
 * 头像
 *
 * @author Created by lucas on 2023/10/16 11:05
 */
class AvatarView(context: Context, attributeSet: AttributeSet) : ConstraintLayout(context, attributeSet) {

    private val mBinding = WidgetAvatarBinding.inflate(LayoutInflater.from(context), this, true)

    fun setImageUrl(url: String?, userId: Long? = null) {
        if (!isShowAvatar(userId)) return
        Glide.with(this)
            .load(ImageUtils.imgPathSmall(url))
            .circleCrop()
            .avatar()
            .into(mBinding.avatar)
    }

    /**
     * 父控件调整了大小，调整avatar大小
     */
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        mBinding.avatar.layout(0, 0, width, height)
    }

    fun setImageUrlMiddle(url: String?, userId: Long? = null) {
        if (!isShowAvatar(userId)) return
        Glide.with(this)
            .load(ImageUtils.imgPathMiddle(url))
            .circleCrop()
            .avatar()
            .into(mBinding.avatar)
    }

    fun setImgPath(url: String?, userId: Long? = null) {
        if (!isShowAvatar(userId)) return
        Glide.with(this)
            .load(ImageUtils.imgPath(url))
            .circleCrop()
            .avatar()
            .into(mBinding.avatar)
    }

    fun setImageResource(@DrawableRes resId: Int, userId: Long? = null) {
        if (!isShowAvatar(userId)) return
        mBinding.avatar.setImageResource(resId)
    }

    private fun isShowAvatar(userId: Long? = null): Boolean {
        return if (userId == UserManager.getUserId() && UserManager.getUser().avatarModified == AppConst.NO) {
            Glide.with(this)
                .load(R.drawable.avatar_default)
                .circleCrop()
                .into(mBinding.avatar)
            false
        } else {
            true
        }
    }
}